import os
import subprocess
import argparse

# 创建命令行参数解析器
parser = argparse.ArgumentParser(description="Generate Markdown file with script output")
parser.add_argument("search_string", help="Search string to be used")
args = parser.parse_args()

# 调用上一个脚本并获取输出
subprocess.call(f"python create_task_list.py {args.search_string}", shell=True)

# 创建输出文件夹
qa_folder = "riscv64"
output_folder = os.path.join(qa_folder, f"{args.search_string}")
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 读取 testlist.txt 文件内容
with open(os.path.join(output_folder, f"testlist.txt"), 'r', encoding='utf-8') as file:
    lines = file.readlines()
    total_lines = len(lines)

# 提取每一行的变量2
variable2_values = []
for line in lines:
    parts = line.strip().split()
    if len(parts) >= 4:
        variable2_values.append(parts[4])
    else:
        variable2_values.append("")

# 生成 Markdown 文件内容
md_content = f"# {args.search_string}\n\n共 {total_lines}个测例\n\n## 测试结果速览\n\n"
md_content += "| 测试用例 | riscv结果 | pr/issue |\n"
md_content += "|-------|------|-------|\n"
for variable2 in variable2_values:
    md_content += f"| {variable2} | | | |\n"
md_content += "### 环境\n"
md_content += "#### riscv\n\nFedora Linux 40 -----> qemu  openEuler riscv 24.03\nriscv镜像地址：https://repo.tarsier-infra.isrc.ac.cn/openEuler-RISC-V/testing/2403LTS-test/v1/\nqemu版本：8.2.0  （qemu版本差异也可能导致问题）\n"
md_content +="\n------\n"
md_content +="## 测试细节\n"

for line in lines:
    parts = line.strip().split()
    if len(parts) >= 4:
        variable2 = parts[4]
    else:
        variable2 = ""
    md_content += f"### {variable2}\n\n{line.strip()}\n\n#### x86\n\n#### riscv\n\n-----\n\n"
md_content += ""
# 输出结果到文件
output_file = os.path.join(output_folder, f"{args.search_string}调研报告.md")
with open(output_file, 'w', encoding='utf-8') as file:
    file.write(md_content)

print(f"Output file '{output_file}' has been generated.")
